package org.mp4.decode;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class Mp4Decode {
    public static void main(String[] args) throws Exception {
        File mp4 = new File("F:\\work\\四川英特\\20240417192358_000019A.MP4");
        FileInputStream stream = new FileInputStream(mp4);

//        MP4 每个段叫一个容器，
//        基本结构是：8 个字节（描述信息）+ N 字节（数据内容）
//        描述信息里面：4 个字节是指长度，后 4 个字节是段名（asii）我们一般命名为skip；
//        4 个字节长度，存储方式 ：
//        按照高位在前低位在后的方法排列，比如长度为 0x12345678,此处存储方式是0x120x34 0x56 0x78. 4
//        个字节长度值的由来 数据内容的长度 + 8。

        int length = stream.available();

        byte[] bytes = toByteArray(stream);

        byte[] lastByte8 = new byte[8];
        System.arraycopy(bytes, bytes.length - 8, lastByte8, 0, 8);

        byte[] lastByte4 = new byte[4];


        System.arraycopy(lastByte8, lastByte8.length - 4, lastByte4, 0, 4);

        int gpsLength = fourbyte2int(lastByte4);




        // 描述信息（4+4）+ 数据内容（N）+ 结束信息（4+4）
        byte[] gpsData = new byte[gpsLength];

        System.arraycopy(bytes, bytes.length - gpsLength-20, gpsData, 0, gpsLength-20);

        byte[] startLastByte4 = new byte[]{gpsData[0],gpsData[1],gpsData[2], gpsData[3]};

//        String gps = new String(gpsData, StandardCharsets.UTF_8);
//        System.out.println(gps);

        System.out.println(fourbyte2int(startLastByte4));

        System.out.println("GPS数据长度："+gpsLength+"\nGPS实际数据："+(gpsData.length-16)+"\nMP4总大小："+bytes.length);


        byte[] mp4Bytes = new byte[bytes.length - gpsLength-20];
        System.arraycopy(bytes, 0, mp4Bytes, 0, bytes.length - gpsLength-20);

        writeByteToFile("F:\\work\\四川英特\\TEST.MP4", mp4Bytes);




        // 打印最后3个元素
        /*for (int i = 0, j = lastByte8.length; i < j; i++) {
            System.out.println("倒数第"+(j-i)+"个："+lastByte8[i]);
        }*/


        /*while (stream.available()!=-1) {

        }*/
    }

    public static void writeByteToFile(String path,byte[] data) {
        try (FileOutputStream fos = new FileOutputStream(path)) {
            fos.write(data); // 将byte数组写入文件
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static int fourbyte2int(byte[] b) {
        return ((((b[0] << 24) & 0xff000000) ^ ((b[1] << 16) & 0x00ff0000))
                ^ ((b[2] << 8) & 0x0000ff00)) ^ (b[3] & 0x000000ff);
    }

    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }
}
